// pages/person/business/entrustBusiness.js
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify'
import { selfServiceList, subOrder, orderPayNotify,querySelfBusinessInfo } from '../../../api/personApply.js'
import { queryAddressinfo } from '../../../api/address.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    backUrl: '/pages/person/business/entrustBusiness',
    overlayShow: false, //遮罩层
    overlayHtml: '支付中',
    serviceList: [],
    scend: 10,
    serviceItemChecked: [],
    serviceCheckList: [],
    totalAmount: '0',
    addressId: '',
    addressInfo: {},
    isAgree: true,
    orderTid: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取地址返回参数
    if(options.paramter != null && options.paramter != '' && options.paramter != undefined){
      this.setData(JSON.parse(options.paramter))
      this.loadAddressinfo()
    }else {
      //读取 代办业务
    selfServiceList().then(res => {
      if(res.code == '0' || res.code == 0){
        this.setData({
          serviceList: res.data
        })
        var totalPrice = 0 // 计算总额
        var i = 0 //list 循环下标
        var checkList = [] //临时存储必选项
        var checkIdList = [] //临时存储必选项id
        for(i; i < res.data.length; i++){
          const personObj = res.data[i]
          if(personObj.isRequired == 1){
            checkList[checkList.length] = personObj
            checkIdList[checkIdList.length] = personObj.id.toString()
            totalPrice = totalPrice + personObj.price
          }
        }
        console.log(checkIdList)
        this.setData({
          serviceCheckList: checkList,
          totalAmount: totalPrice,
          serviceItemChecked: checkIdList
        })
      }else {
        Notify({ type: 'danger', message: res.msg })
      }
    }).catch(err=>{
      Notify({ type: 'danger', message: err })
    });
    }
  },
  //查询地址详情
  loadAddressinfo(){
    queryAddressinfo(this.data.addressId).then(res => {
      this.setData({
        addressInfo: res
      })
    }).catch(err=>{
      Notify({ type: 'danger', message: err })
    });
  },
  //服务项选择
  onServiceItemChange: function(event){
    const checkList = []
    this.data.serviceList.forEach(element => {
      const a = event.detail
      if(a.indexOf(element.id.toString()) >= 0 || element.isRequired==1){
        checkList[checkList.length] = element
      }
    });
    this.setData({
      totalAmount: '0'
    })
    checkList.forEach(e =>{
      const addPrice = parseFloat(this.data.totalAmount) + e.price
      this.setData({
        totalAmount: addPrice
      })
    })
    console.log(event.detail)
    this.setData({
      serviceItemChecked: event.detail,
      serviceCheckList: checkList
    });
  },
  //跳转地址选择
  addressChange: function(e){

    wx.navigateTo({
      url: '/pages/person/address/address?paramter='+JSON.stringify(this.data)
    })
  },
  /** 是否同意个体户协议 */
  onChangeAgree: function(){
    const agree = this.data.isAgree
    this.setData({
      isAgree: (agree == true ? false: true)
    })
  },
  /**
   * 跳转个体户 协议
   */
  clickAgree: function(){
    wx.navigateTo({
      url: '/pages/person/agree/personAgree',
    })
  },
  //提交订单
  subForm: function() {
    
    if(this.data.addressId=='' || this.data.addressId==undefined  || this.data.addressId==null){
      Notify({ type: 'danger', message: '请选择收件地址'})
      return false
    }
    if(this.data.serviceCheckList.length == 0){
      Notify({ type: 'danger', message: '请选择服务项目'})
      return false
    }
    const checkServiceIdArr = []
    this.data.serviceCheckList.forEach(e=>{
      checkServiceIdArr[checkServiceIdArr.length] = e.id
    })

    const paramgs = {
      serviceIdArr: checkServiceIdArr,
      addressId: this.data.addressId,
      goodsType: 1
    }
    //开启遮罩层
    this.setData({
      'overlayShow': true
    })
    var _this = this
    //提交订单
    subOrder(paramgs).then(res => {
      if(res.code != '0' && res.code != 0){
        //支付失败 隐藏遮罩层
        _this.overlayHide()
        Notify({ type: 'danger', message: res.msg })
      } else {
        _this.setData({
          orderTid: res.data.tid
        })
        _this.payOrder(res);
      }
    }).catch(err=>{
      //支付失败 隐藏遮罩层
      _this.overlayHide()
      Notify({ type: 'danger', message: err.sub_msg })
    });
  },
  // 隐藏遮罩层
  overlayHide: function() {
    this.setData({
      'overlayShow': false,
      'overlayHtml': '支付中...'
    })
  },
  /** 发起支付请求 */
  payOrder(res) {
    var _this = this
    wx.requestPayment({
      nonceStr: res.wxPayParamter.nonceStr,
      package: res.wxPayParamter.packageValue,
      paySign: res.wxPayParamter.paySign,
      timeStamp: res.wxPayParamter.timeStamp,
      signType: res.wxPayParamter.signType,
      success (res) { 
        const requestPayment = res.errMsg.split(":");
        if(requestPayment[1] == 'ok'){
          _this.payOrderSuccess();
        }else {
          //隐藏遮罩层
          _this.overlayHide()
        }
        
      },
      fail (res) {
        //隐藏遮罩层
        _this.overlayHide()
        const requestPayment = res.errMsg.split(":")
        const errMsg = requestPayment[1].split(" ");
        if(errMsg.length > 1 && errMsg[1] == 'cancel'){
          //取消支付
          Notify({ type: 'danger', message: "取消支付" })
        }else {
          //支付失败处理
          Notify({ type: 'danger', message: "支付失败" })
        }
       }
    })
  },
  /**
   * 订单支付成功
   */
  payOrderSuccess: function() {
    let _this = this
    this.setData({
      'overlayHtml': '查询支付结果...'
    })
    let data = {
      'orderTid': this.data.orderTid
    }
    orderPayNotify(data).then(res => {
      if(res.code != '0' && res.code != 0){
        //异常 隐藏遮罩层
        _this.overlayHide()
        Notify({ type: 'danger', message: res.msg })
      }else {
        // 支付成功 查询个体户
        _this.countdown()
      }
    }).catch(err => {
      //异常 隐藏遮罩层
      _this.overlayHide()
      Notify({ type: 'danger', message: err.sub_msg })
    })
  },
  loadPerson: function() {
    var _this = this
    querySelfBusinessInfo().then(res => {
      console.log(res)
      if(res.payStatus == 2 || res.payStatus == 4){
        this.setData({
          scend: -1
        })
        Notify({ type: 'success', message: "查询成功，正在跳转" })
        this.overlayHide()
        wx.reLaunch({
          url: '../progress/progress',
        })
      }else {
        _this.countdown()
      }
    }).catch(err=> {
      Notify({ type: 'danger', message: err })
      _this.countdown()
    })
  },
  countdown() {
    if(this.data.scend == 0){
      Notify({ type: 'danger', message: "无查询结果，请联系客服" })
      this.overlayHide()
      return;
    }
    if(this.data.scend == -1){
      this.setData({
        scend: 10
      })
      this.overlayHide()
      return;
    }
    var _this = this
    var timer = setTimeout(function () {
      var scendIn = _this.data.scend - 1;
      _this.setData({
        scend: scendIn
      })
      _this.loadPerson()
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})